# -!- coding: utf-8 -!-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者：cacho_37967865
#博客：https://blog.csdn.net/sinat_37967865
#文件：baseModel.py
#日期：2019-07-02
#备注：图片进行base64编码，解码
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import base64
import os
from pycacho.cachobase.file_deal import w_save_txt


# 对bytes类型进行再次编码(先将字符串转换为byttes)
def base_info():
    str = '将要加密的数据'
    #e = base64.b64encode(b"123456")       # 结果：b'MTIzNDU2'
    e = base64.b64encode(str.encode())     # 结果：b'5oiR5Zac5qyiIGNvbXB1dGVy'
    print("编码过程：",e)
    d = base64.b64decode(b'5oiR5Zac5qyiIGNvbXB1dGVy')
    print(d)
    print("解码过程：",d.decode())


def encode_base64(file):
    with open(file,'rb') as f:
        f_data = f.read()
        base64_data = base64.b64encode(f_data)
        file_type = file.split('.')[1]
        if file_type=='jpg':
            base64_str = 'data:image/jpeg;base64,' + str(base64_data, 'utf-8')
        elif file_type=='png':
            base64_str = 'data:image/png;base64,' + str(base64_data, 'utf-8')
        else:
            base64_str =  str(base64_data, 'utf-8')            # 'data:application/pdf;base64,'
        #print(type(base64_data))
        # 如果想要在浏览器上访问base64格式图片，需要在前面加上：'data:image/jpeg;base64,'
        #w_save_txt('E:\zenglingwei\logs\\base.txt', base64_str)
        return base64_str


def decode_base64(base64_data):
    with open('./images/base64.jpg','wb') as file:
        img = base64.b64decode(base64_data)
        file.write(img)


if __name__ == '__main__':
    file_path = 'E:\zenglingwei\\test\\c.png'
    base_info()
    #base64_data = encode_base64(file_path)
    #decode_base64(base64_data)